package com.nhjf.admin.controller.followThePainting;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.nhjf.admin.common.util.ImageTools;
import com.nhjf.admin.common.util.SysProperties;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.command.followThePainting.FollowThePaintingCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.model.followThePainting.FollowThePainting;
import com.nhjf.model.followThePainting.followThePaintingDetails.FollowThePaintingDetails;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.CoursesType;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.followThePainting.FollowThePaintingQo;
import com.nhjf.pojo.qo.followThePainting.followThePaintingDetailsQo.FollowThePaintingDetailsQo;
import com.nhjf.pojo.qo.teachers.CoursesTypeQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.followThePainting.FollowThePaintingService;
import com.nhjf.service.followThePainting.followThePaintingDetails.FollowThePaintingDetailsService;
import com.nhjf.service.teachers.CoursesTypeService;
import com.nhjf.service.teachers.TeachersService;

import net.sf.json.JSONObject;

@RequestMapping("/ftp")
@Controller
public class FollowThePaintingController {

	@Autowired
	private FollowThePaintingService followThePaintingService;
	@Autowired
	private FollowThePaintingDetailsService followThePaintingDetailsService;
	@Autowired
	private TeachersService teachersService;
	@Autowired
	private CoursesTypeService coursesTypeService;
	
	@ResponseBody
	@RequestMapping("/coursesType_Subctype")
	public String showSubctype(HttpServletRequest request, HttpServletResponse response, Model model,String typeOne) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
			coursesTypeQo.setpId(Long.parseLong(typeOne));
			coursesTypeQo.setType(2);
			List<CoursesType> list=coursesTypeService.queryList(coursesTypeQo);
			if(list!=null) {
				resMap.put("code", "200");
				resMap.put("message", list);
				return JSONObject.fromObject(resMap).toString();
			}else {
				return "404";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
	}

	//跟着画列表
	@RequestMapping("/followThePainting_list")
	public String followThePainting(@RequestParam(value = "page", defaultValue = "1")Integer page,String type,Model model,FollowThePaintingQo followThePaintingQo,HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role roles=new Role();
			while(iter.hasNext()) {
				roles=iter.next();
				break;
			}
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}

			if("1".equals(roles.getNumber())) {
				if(StringUtils.isNotEmpty(type)){
					followThePaintingQo.setTypeOne(Long.parseLong(type));
				}
				CoursesTypeQo qo=new CoursesTypeQo();
				qo.setType(1);
				List<CoursesType> coursesTypeList = coursesTypeService.queryList(qo);
				model.addAttribute("coursesTypeList",coursesTypeList);
				followThePaintingQo.setSeachTypeOne(true);
				followThePaintingQo.setSeachTypeTwo(true);
				followThePaintingQo.setSeachTeacher(true);
				
				Pagination pagination = new Pagination();
				pagination.setPageSize(6);
				pagination.setPageNo(page);
				pagination.setCondition(followThePaintingQo);
				pagination = followThePaintingService.queryPagination(pagination);
				SysProperties sysProperties=SysProperties.getInstance();
				String webPath=sysProperties.get("webPath");
				model.addAttribute("pagination",pagination);
				model.addAttribute("webPath",webPath);
				model.addAttribute("CoursesQo", followThePaintingQo);
				return "/folloThePainting/follow.html";
			} else if("3".equals(roles.getNumber()) || "2".equals(roles.getNumber())) {
				if(StringUtils.isNotEmpty(type)){
					followThePaintingQo.setTypeOne(Long.parseLong(type));
				}
				CoursesTypeQo qo=new CoursesTypeQo();
				qo.setType(1);
				List<CoursesType> coursesTypeList = coursesTypeService.queryList(qo);
				model.addAttribute("coursesTypeList",coursesTypeList);
				followThePaintingQo.setSeachTypeOne(true);
				followThePaintingQo.setSeachTypeTwo(true);
				followThePaintingQo.setSeachTeacher(true);
				TeachersQo teachersQo=new  TeachersQo();
				teachersQo.setUserId(user.getId());
				Teacher teacher= teachersService.queryUnique(teachersQo);
				followThePaintingQo.setUploader(teacher.getId());
				Pagination pagination = new Pagination();
				pagination.setPageNo(page);
				pagination.setPageSize(6);
				pagination.setCondition(followThePaintingQo);
				pagination = followThePaintingService.queryPagination(pagination);
				SysProperties sysProperties=SysProperties.getInstance();
				String webPath=sysProperties.get("webPath");
				model.addAttribute("pagination",pagination);
				model.addAttribute("webPath",webPath);
				model.addAttribute("CoursesQo", followThePaintingQo);
				return "/folloThePainting/follow.html";
			}


			return "500";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常");
			return JSONObject.fromObject(resMap).toString();
		}
	}
	@ResponseBody
	@RequestMapping("/followThePainting_save")
	public String followThePaintingSave(@RequestParam("files") MultipartFile[] files,@RequestParam("imag")MultipartFile imag,HttpServletRequest request,HttpServletResponse response,FollowThePaintingCommand command) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		String ids="11";
		try {
			if(files.length<1) {
				resMap.put("code", "500");
				resMap.put("message", "请选择要上传的图片！");
				return JSONObject.fromObject(resMap).toString();
			}
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role roles=new Role();
			while(iter.hasNext()) {
				roles=iter.next();
				break;
			}
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			List<String> strlist=new ArrayList<String>();
			String dateString= new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			for (int i=1 ;i<=files.length;i++ ) {
				int returnTag = -1;
				SysProperties sysProperties=SysProperties.getInstance();

				String followThePicture=sysProperties.get("followThePicture");
				//获取图片原始文件名
				String finetTalk = files[i-1].getOriginalFilename();
				System.out.println(finetTalk);
				//文件名使用当前时间
				String name = dateString+"-"+i;
				// 获取上传图片的扩展名(jpg/png/...)
				String extension = FilenameUtils.getExtension(finetTalk);
				String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
				boolean flag = false;
				// 判断文件格式是否合法
				for (String str : regular) {
					if (extension.equalsIgnoreCase(str)) {
						flag = true;
					}
				}
				if (!flag) {
					returnTag = 0;
					resMap.put("code", "500");
					resMap.put("message", "上传图片格式不正确！");
					return JSONObject.fromObject(resMap).toString();
				}
				// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
				String path =followThePicture+"/"+user.getId() +"/" +name + "." + extension;
				strlist.add(user.getId() +"/" +name + "." + extension);
				//图片上传的绝对路径

				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				// 上传图片
				files[i-1].transferTo(new File(path));
				command.setImgList(strlist);
			}
			if (imag.isEmpty()) {
				resMap.put("code", "500");
				resMap.put("message", "上传图片不可为空");
				return JSONObject.fromObject(resMap).toString();
			}
			int returnTag = -1;
			SysProperties sysProperties=SysProperties.getInstance();
			String followThePicture=sysProperties.get("followThePicture");
			//获取图片原始文件名
			String finetTalk = imag.getOriginalFilename();
			System.out.println(finetTalk);
			//文件名使用当前时间
			String name = dateString+"-1";
			// 获取上传图片的扩展名(jpg/png/...)
			String extension = FilenameUtils.getExtension(finetTalk);
			String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
			boolean flag = false;
			// 判断文件格式是否合法
			for (String str : regular) {
				if (extension.equalsIgnoreCase(str)) {
					flag = true;
				}
			}
			if (!flag) {
				returnTag = 0;
				resMap.put("code", "500");
				resMap.put("message", "上传图片格式不正确！");
				return JSONObject.fromObject(resMap).toString();
			}
			// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）

			String path =followThePicture+"/"+user.getId()+"/" +name + "." + extension;
			//图片上传的绝对路径

			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 上传图片
			imag.transferTo(new File(path));
			int width=ImageTools.getImgWidth(dir);
			int height=ImageTools.getImgHeight(dir);
			command.setWidth(width);
			command.setHeight(height);
			Long i=user.getId();
			String userId;
			userId=i+"";
			command.setTeacherName(userId);
			command.setCover(user.getId()+"/" +name + "." + extension);
			ServiceResultDto dto=followThePaintingService.createFollowThePaintingComment(command);
			if(dto.getSuccess()) {
				resMap.put("code", "200");
				resMap.put("message", "上传成功");
				return JSONObject.fromObject(resMap).toString();
			}else {
				return "500";
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resMap.put("code", "500");
		resMap.put("message", "系统异常");
		return JSONObject.fromObject(resMap).toString();
	}
	@ResponseBody
	@RequestMapping("/followThePainting_delete")
	public String deleteFollowThePainting(String id) {
		Map<String, Object> resMap=new HashMap<String, Object>();

		try {
			FollowThePaintingQo followThePaintingQo=new FollowThePaintingQo();
			followThePaintingQo.setFollowThePaintingId(Long.parseLong(id));
			FollowThePainting followThePainting= followThePaintingService.queryUnique(followThePaintingQo);
			FollowThePaintingDetailsQo detailsQo=new FollowThePaintingDetailsQo();
			detailsQo.setFollowThePaintingId(Long.parseLong(id));
			List<FollowThePaintingDetails> fList= followThePaintingDetailsService.queryList(detailsQo);
			Long[] longId=new Long[fList.size()];
			for(int i=0;i<fList.size();i++) {
				longId[i]=fList.get(i).getId();
				SysProperties sysProperties=SysProperties.getInstance();
				String imgPath=sysProperties.get("imagePath");
				File dest = new File(imgPath+fList.get(i).getDetailPicture());
				// 路径为文件且不为空则进行删除  
				if (dest.isFile() && dest.exists()) {  
					dest.delete();  
				}
			}
			SysProperties sysProperties=SysProperties.getInstance();
			String imgPath=sysProperties.get("imagePath");
			File dest = new File(imgPath+followThePainting.getCover());
			// 路径为文件且不为空则进行删除  
			if (dest.isFile() && dest.exists()) {  
				dest.delete();  
			}
			followThePaintingDetailsService.deleteByIds(longId);
			followThePaintingService.deleteById(Long.parseLong(id));

			return "200";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "500";
	}
	@RequestMapping("/tz_folloAdd")
	public String tz_folloAdd(Model model) {
		CoursesTypeQo qo=new CoursesTypeQo();
		qo.setType(1);
		List<CoursesType> coursesTypeList = coursesTypeService.queryList(qo);
		model.addAttribute("coursesTypeList",coursesTypeList);
		return "/folloThePainting/up.html";
	}
}
